package com.cheyun.netsalev3.viewmodel

import android.media.MediaPlayer
import android.view.View
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.runOnIoThread
import com.cheyun.netsalev3.utils.runoopThread

class CallPopFragmentViewModel(url: String, var starttime: String, var timesName: String) : BaseViewModel() {
    private val mediaPlayer: MediaPlayer = MediaPlayer()
    //持续时间显示使用
    val duration = ObservableField<String>()
    var durationTime = MutableLiveData<Long>()
    //是否播放
    var isPay = ObservableField<Boolean>(false)
    //当前时间
    var currentime = MutableLiveData<Int>()

    val currentimeShow = ObservableField<String>()

    init {
        runOnIoThread {
            mediaPlayer.setDataSource(url)
            mediaPlayer.prepare()
        }
        mediaPlayer.setOnPreparedListener {
            var time = mediaPlayer.duration / 1000.toLong()
            durationTime.postValue(time)
            var shouwTime = FunctionUtils.formatSeconds(time)
            duration.set(shouwTime)

            runoopThread {
                val currentPosition = mediaPlayer.currentPosition / 1000
                var shouwTime = FunctionUtils.formatSeconds(currentPosition.toLong())
                currentimeShow.set(shouwTime)
                currentime.postValue(currentPosition)
            }
        }

        mediaPlayer.setOnCompletionListener {
            isPay.set(false)
        }
    }

    override fun onCleared() {
        super.onCleared()
        mediaPlayer?.release()
    }

    /**
     * 跳转
     */
    fun seekTo(userSelectedPosition: Int) {
        runOnIoThread {
            mediaPlayer.seekTo(userSelectedPosition*1000)
        }
    }

    /**
     * 点击开始或者暂停
     */
    fun onClickPay(view: View) {
        isPay.get()?.apply {
            if (this) {
                //暂停播放
                isPay.set(false)
                runOnIoThread {
                    mediaPlayer.pause()
                }
            } else {
                //开始
                isPay.set(true)
                runOnIoThread {
                    mediaPlayer.start()
                }
            }
        }
    }
}